import React from "react";
import { Link } from "react-router-dom";
import { createForm } from "@formily/core";
import { createSchemaField, ISchema } from "@formily/react";
import localStorage from "store2";
import api from "src/http/api";
import { UserInfoContext } from "src/App";

import { Form, FormItem, Input, Submit, FormProps } from "@formily/antd";
import { Typography, notification } from "antd";
import UserInfo from ".";
import AvatarUpload from "src/components/AvatarUpload";

const { useEffect, useContext } = React;

const Modify: React.FC = (props) => {
  const context = useContext(UserInfoContext);
  const form = createForm();
  const SchemaField = createSchemaField({
    components: {
      FormItem,
      Input,
      AvatarUpload,
    },
  });

  const formProps: FormProps = {
    form,
    layout: "vertical",
    size: "large",
    style: { width: 550, padding: "24px 48px" },
    onAutoSubmit: (formData) => {
      const avatar =
        formData.avatar[0].response?.data?.url || context.userInfo.avatar;
      const userInfo = { ...formData, avatar };
      api.modifyUser(userInfo).then(() => {
        localStorage.set("userInfo", userInfo);
        context.setUserInfo(userInfo);
        notification.success({
          message: "Success",
          description: "修改基本信息成功",
          top: 65,
        });
      });
    },
  };

  const schema: ISchema = {
    type: "object",
    properties: {
      username: {
        type: "string",
        title: "用户名",
        required: true,
        "x-decorator": "FormItem",
        "x-component": "Input",
      },
      email: {
        type: "string",
        title: "邮箱",
        required: true,
        format: "email",
        "x-decorator": "FormItem",
        "x-component": "Input",
        "x-disabled": true,
      },
      avatar: {
        type: "array",
        title: "头像",
        required: true,
        "x-decorator": "FormItem",
        "x-component": "AvatarUpload",
      },
    },
  };

  useEffect(() => {
    const avatar = [{ url: context.userInfo.avatar }];
    form.setInitialValues({ ...context.userInfo, avatar });
  });

  return (
    <UserInfo>
      <Form {...formProps}>
        <Typography.Title level={2}>修改基础信息</Typography.Title>
        <SchemaField schema={schema} />
        <Submit block size="large">
          提交
        </Submit>
        <Link to="/modifyPassword" style={{ display: "block", marginTop: 12 }}>
          修改密码
        </Link>
      </Form>
    </UserInfo>
  );
};

export default Modify;
